<template>
  <view v-if="success == 1">
    <view class="message_list" :style="windowHeight">
      <view class="message_item" v-for="(item, i) in messageList" :key="i">
        <view class="show_hide" v-if="item.openid">
          <view v-if="item.showTime">
            <changeTime :timer="item.showTime"></changeTime>
          </view>
          <view class="message_right" v-if="openid_right == item.openid">
            <view class="picture" v-if="item.content_pic">
              <image :src="item.content_pic" mode="widthFix" @click="getImage(item.content_pic)"></image>
            </view>
            <view class="text" v-else>
              {{item.content_text}}
            </view>
            <view class="triangle" v-if="item.content_text"></view>
            <image :src="avatar_right" class="avatarUrl"></image>
          </view>
          <view class="message_left" v-else>
            <image :src="avatar_left" class="avatarUrl"></image>

            <view class="triangle" v-if="item.content_text"></view>
            <view class="picture" v-if="item.content_pic">
              <image :src="item.content_pic" mode="widthFix" @click="getImage(item.content_pic)"></image>
            </view>
            <view class="text" v-else>
              {{item.content_text}}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="bottom_area">
      <!-- 占位 -->
    </view>

    <view class="bottom_box">
      <textarea cols="30" rows="10" hold-keyboard="true" v-model="chatModule.content[0].content_text" autoHeight
        cursor-spacing="20rpx" class="inputText" :fixed="true" :show-confirm-bar=hide @click="gotoBottom()"></textarea>
      <button @click="send" class="sendButton" :style="sendChange" @touchstart="start" @touchend="end" v-if="chatModule.content[0].content_text">发送</button>
      <uni-icons type="images" color="#969696" size="60rpx" class="sendPic" @click="sendPic" v-else></uni-icons>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        messageList: [],
        dataMessage: [],
        openid_left: '',
        openid_right: '',
        avatar_left: '',
        avatar_right: '',
        changeHeight: 1,
        user_array: '',
        windowHeight: 'min-height: 0rpx',
        scrollHeight: '',
        hide: false,
        sendChange: '',
        stop: 0,
        success: 0,
        urls: [],
        chatModule: {
          both_openid: [],
          browse: false,
          lastOpenid: '',
          avatarUrl: [],
          nickName: [],
          content: [{
            c_id: "",
            content_text: "",
            openid: "",
            showTime: ""
          }]
        },
        noMessage: 0,
        hideWeb: 0
      };
    },
    onLoad(options) {
      this.searchChatModule(options.openid)
      this.openid_left = options.openid
      uni.getSystemInfo({
        success: (res) => {
          // 宽度倍数
          const multiple = res.windowWidth * 2 / 750
          this.windowHeight = 'min-height: ' + (res.windowHeight * 2 / multiple - 119) + 'rpx'
        }
      })
      this._freshing = false;
    },
    onShow() {
      this.freashMessage()
    },
    onUnload() {
      const lastMessage = this.messageList.slice(-1)
      const my_openid = this.openid_right
      if(lastMessage[0].openid !== my_openid) {
        uniCloud.callFunction({
          name: 'updateContentBrowse',
          data: {
            a: this.chatModule.both_openid[0],
            b: this.chatModule.both_openid[1]
          }
        })
      }
      this.fresh().then(e => {
        this.hideWeb = 1
      })
    },
    onPullDownRefresh() {
      const res = uni.getStorageSync(this.user_array)
      if (res) {
        if (JSON.parse(res).length - this.messageList.length > 25) {
          this.messageList = JSON.parse(res).slice(JSON.parse(res).length - this.messageList.length - 25)
          setTimeout(function() {
            uni.stopPullDownRefresh();
          }, 500);
          this.distance()
        } else {
          if (this.noMessage == 0) {
            this.noMessage = 1
            this.messageList = JSON.parse(res).slice(0)
            setTimeout(function() {
              uni.stopPullDownRefresh();
            }, 500);
            uni.showToast({
              title: '没有更多消息啦',
              icon: "none",
              duration: 1000, // 当然这个时间可根据实用场景进行相关设置
            })
            this.distance()
          } else {
            setTimeout(function() {
              uni.stopPullDownRefresh();
            }, 500);
          }
        }
      }
    },
    methods: {
      start() {
        this.sendChange = 'background: rgba(47, 231, 103, .8);'
      },
      end() {
        this.sendChange = 'background: rgba(47, 231, 103, 1);'
      },
      // 查看图片
      getImage(url) {
        this.urls = []
        this.messageList.map( e => {
          if(e.content_pic !== undefined && e.content_pic !== '') {
            this.urls.push(e.content_pic)
          }
        })
        uni.previewImage({
          urls: this.urls,
          current: url
        })
      },
      disposeTime(time) {
        const data = uni.getStorageSync(this.user_array)
        const lastTime = JSON.parse(data).slice(-1)[0].c_id
        var day1 = time.split(' ')[0].split('-')[2]
        var day2 = lastTime.split(' ')[0].split('-')[2]
        if (day1 == day2) {
          var month1 = time.split(' ')[0].split('-')[1]
          var month2 = lastTime.split(' ')[0].split('-')[1]
          if (month1 == month2) {
            var year1 = time.split(' ')[0].split('-')[0]
            var year2 = lastTime.split(' ')[0].split('-')[0]
            if (year1 == year2) {
              var first_time = time.split(' ')[1]
              var second_time = lastTime.split(' ')[1]
              var h1 = first_time.split(':')[0]
              var h2 = second_time.split(':')[0]
              var m1 = first_time.split(':')[1]
              var m2 = second_time.split(':')[1]
              var gap = h1 - h2
              if (gap == 0) {
                if (m1 - m2 >= 5) {
                  return time
                } else {
                  return ''
                }
              } else if (gap == 1) {
                if (60 + (m1 - m2) >= 5) {
                  return time
                } else {
                  return ''
                }
              } else {
                return time
              }
            } else {
              return time
            }
          } else {
            return time
          }
        } else {
          return time
        }
      },
      // 下拉刷新滚动
      distance() {
        const query = uni.createSelectorQuery().in(this);
        query.select('.message_list').boundingClientRect(data => {
        }).exec(res => {
          this.oldBottom = this.newBottom
          this.newBottom = res[0].height
          this.scrollDistance = this.newBottom - this.oldBottom
          uni.pageScrollTo({
            scrollTop: this.scrollDistance,
            duration: 0
          })
        });
      },
      // 格式化时间
      formatDate(datetime) {
        var date = new Date(datetime) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var year = date.getFullYear()
        var month = ('0' + (date.getMonth() + 1)).slice(-2)
        var sdate = ('0' + date.getDate()).slice(-2)
        var hour = ('0' + date.getHours()).slice(-2)
        var minute = ('0' + date.getMinutes()).slice(-2)
        var second = ('0' + date.getSeconds()).slice(-2)
        // 拼接
        var result = year + '-' + month + '-' + sdate + ' ' + hour + ':' + minute + ':' + second
        // 返回
        return result
      },
      // 初始化 创建或搜索聊天室
      async searchChatModule(one_openid) {
        // 将对方的openid存储在数组里
        this.chatModule.both_openid.push(one_openid)
        // 获取对方用户头像
        uniCloud.callFunction({
          name: 'getUser',
          data: {
            openID: one_openid
          },
          success: (res) => {
            this.avatar_left = res.result.data[0].avatarUrl
            this.chatModule.avatarUrl.push(res.result.data[0].avatarUrl)
            this.chatModule.nickName.push(res.result.data[0].nickName)
            uni.setNavigationBarTitle({
              title: res.result.data[0].nickName,
            });
            // 将我的openid存储在数组里
            const two_openid = uni.getStorageSync('jiayi_openid')
            this.openid_right = two_openid
            uniCloud.callFunction({
              name: 'getUser',
              data: {
                openID: two_openid
              },
              success: (res) => {
                this.avatar_right = res.result.data[0].avatarUrl
                this.chatModule.avatarUrl.push(res.result.data[0].avatarUrl)
                this.chatModule.nickName.push(res.result.data[0].nickName)
                if (one_openid !== two_openid) {
                  this.chatModule.both_openid.push(two_openid)
                  this.user_array = one_openid + '&' + two_openid
                  const storageDate = uni.getStorageSync(this.user_array)
                  uniCloud.callFunction({
                    name: 'getContent',
                    data: {
                      a: this.chatModule.both_openid[0],
                      b: this.chatModule.both_openid[1]
                    },
                    success: async (e) => {
                      if (e.result.data.length == 0) {
                        uniCloud.callFunction({
                          name: 'addContent',
                          data: this.chatModule
                        })
                      } else {
                        if (e.result.data[0].avatarUrl.indexOf(this.chatModule.avatarUrl[0]) == -1 || e.result.data[0].avatarUrl.indexOf(this.chatModule.avatarUrl[1]) == -1) {
                          uniCloud.callFunction({
                            name: 'updateContentUser',
                            data: {
                              a: this.chatModule.both_openid[0],
                              b: this.chatModule.both_openid[1],
                              c: {
                                avatarUrl: this.chatModule.avatarUrl
                              }
                            }
                          })
                        }
                        if (e.result.data[0].nickName.indexOf(this.chatModule.nickName[0]) == -1 || e.result.data[0].nickName.indexOf(this.chatModule.nickName[1]) == -1) {
                          uniCloud.callFunction({
                            name: 'updateContentUser',
                            data: {
                              a: this.chatModule.both_openid[0],
                              b: this.chatModule.both_openid[1],
                              c: {
                                nickName: this.chatModule.nickName
                              }
                            }
                          })
                        }
                      }
                      if (storageDate) {
                        // 初始化时获取数据的后25条数据
                        if(JSON.parse(storageDate).length > 25) {
                          this.messageList = JSON.parse(storageDate).slice(e.result.data[0].content.length - 26)
                          this.fresh().then(a => {
                            this.gotoBottom()
                          })
                        } else {
                          this.messageList = JSON.parse(storageDate)
                          this.fresh().then(a => {
                            this.gotoBottom()
                          })
                        }
                        // 初始化页面下滑到底部
                        this.gotoBottom()
                      } else {
                        uni.setStorageSync(this.user_array, JSON.stringify([{
                          c_id: "",
                          content_text: "",
                          openid: ""
                        }]))
                      }
                    },
                  })
                } else {
                  // 用户对自己发起聊天
                  this.chatModule.both_openid.push("myself")
                  this.user_array = one_openid + '&' + 'myself'
                  const storageDate = uni.getStorageSync(this.user_array)
                  uniCloud.callFunction({
                    name: 'getContent',
                    data: {
                      a: this.chatModule.both_openid[0],
                      b: this.chatModule.both_openid[1]
                    },
                    success: (e) => {
                      if (e.result.data.length == 0) {
                        uniCloud.callFunction({
                          name: 'addContent',
                          data: this.chatModule
                        })
                      } else {
                        if (e.result.data[0].avatarUrl !== this.chatModule.avatarUrl) {
                          uniCloud.callFunction({
                            name: 'updateContentUser',
                            data: {
                              a: this.chatModule.both_openid[0],
                              b: this.chatModule.both_openid[1],
                              c: {
                                avatarUrl: this.chatModule.avatarUrl
                              }
                            }
                          })
                        }
                        if (e.result.data[0].nickName !== this.chatModule.nickName) {
                          uniCloud.callFunction({
                            name: 'updateContentUser',
                            data: {
                              a: this.chatModule.both_openid[0],
                              b: this.chatModule.both_openid[1],
                              c: {
                                nickName: this.chatModule.nickName
                              }
                            }
                          })
                        }
                      }
                      if (storageDate) {
                        // 初始化时获取数据的后25条数据
                        if(JSON.parse(storageDate).length > 25) {
                          this.messageList = JSON.parse(storageDate).slice(e.result.data[0].content.length - 26)
                          this.fresh().then(a => {
                            this.gotoBottom()
                          })
                        } else {
                          this.messageList = JSON.parse(storageDate)
                          this.fresh().then(a => {
                            this.gotoBottom()
                          })
                        }
                      } else {
                        uni.setStorageSync(this.user_array, JSON.stringify([{
                          c_id: "",
                          content_text: "",
                          openid: ""
                        }]))
                      }
                    }
                  })
                }
                this.success = 1
              }
            })
          }
        })
      },
      // 发送消息
      send() {
        if (this.stop == 0) {
          this.stop = 1
          if (this.chatModule.content[0].content_text.replace(/ |\n/g, "") == "") {
            this.stop = 0
            uni.showToast({
              title: "不能发送空白消息",
              icon: "none",
              duration: 1500
            })
          } else {
            // 获取当前时间并格式化
            var date = new Date()
            var dateTime = date.getTime()
            // 格式化时间
            const dealTime = this.formatDate(dateTime)
            // 判断发消息的时间间隔是否超过5分钟
            const showTime = this.disposeTime(dealTime)
            if (showTime !== '') {
              this.chatModule.content[0].showTime = showTime
            }
            this.chatModule.content[0].c_id = dealTime
            this.chatModule.content[0].openid = uni.getStorageSync('jiayi_openid')
            // 向本地存储添加内容
            const data = JSON.parse(uni.getStorageSync(this.user_array))
            data.push(this.chatModule.content[0])
            uni.setStorageSync(this.user_array, JSON.stringify(data))
            // 向数据库添加内容
            uniCloud.callFunction({
              name: 'updateContent',
              data: {
                a: this.chatModule.both_openid[0],
                b: this.chatModule.both_openid[1],
                c: this.chatModule.content,
                d: this.openid_right
              },
              success: async (e) => {
                const db = uniCloud.database()
                const dbCmd = db.command
                const collection = db.collection('jiayi-content')
                const res = await collection.where({
                  both_openid: dbCmd.eq(this.chatModule.both_openid[0]).and(dbCmd.eq(this.chatModule
                    .both_openid[1]))
                }).get()
                this.messageList = res.result.data[0].content
                this.chatModule.content[0].content_text = ''
                this.chatModule.content[0].showTime = ''
                this.gotoBottom()
                this.stop = 0
              },
            })
          }
        }
      },
      // 定时刷新聊天数据
      freashMessage() {
          this.timer = setInterval(async () => {
            if(this.hideWeb == 0) {
              this.fresh()
            }
          }, 2500)
      },
      async fresh() {
          const db = uniCloud.database()
          const dbCmd = db.command
          const collection = db.collection('jiayi-content')
          const res = await collection.where({
            both_openid: dbCmd.eq(this.chatModule.both_openid[0]).and(dbCmd.eq(this.chatModule.both_openid[
              1]))
          }).get()
          const messageDate = JSON.parse(uni.getStorageSync(this.user_array))
          // 数据之间相差的长度
          const long = res.result.data[0].content.length - messageDate.length
          const data = res.result.data[0].content
          const newPushData = data.slice(res.result.data[0].content.length - long)
          if (newPushData.length !== 0) {
            newPushData.map(x => {
              messageDate.push(x)
              this.messageList.push(x)
            })
            uni.setStorageSync(this.user_array, JSON.stringify(messageDate))
          }
      },
      sendPic() {
        uni.chooseImage({
          count: 1,
          success: (sign) => {
            if (sign.tempFilePaths.length > 0) {
              let filePath = sign.tempFilePaths[0]
              //进行上传操作
              // promise方式
              uniCloud.uploadFile({
                filePath: filePath,
                cloudPath: 'contact.jpg',
                success: (res) => {
                  var date = new Date()
                  var dateTime = date.getTime()
                  this.chatModule.content[0].c_id = this.formatDate(dateTime)
                  this.chatModule.content[0].openid = uni.getStorageSync('jiayi_openid')
                  this.chatModule.content[0].content_pic = res.fileID
                  // 向本地存储添加内容
                  const data = JSON.parse(uni.getStorageSync(this.user_array))
                  data.push(this.chatModule.content[0])
                  uni.setStorageSync(this.user_array, JSON.stringify(data))
                  // 向数据库添加内容
                  uniCloud.callFunction({
                    name: 'updateContent',
                    data: {
                      a: this.chatModule.both_openid[0],
                      b: this.chatModule.both_openid[1],
                      c: this.chatModule.content
                    },
                    success: async (e) => {
                      const db = uniCloud.database()
                      const dbCmd = db.command
                      const collection = db.collection('jiayi-content')
                      const res = await collection.where({
                        both_openid: dbCmd.eq(this.chatModule.both_openid[0]).and(dbCmd.eq(this
                          .chatModule.both_openid[1]))
                      }).get()
                      this.messageList = res.result.data[0].content
                      this.chatModule.content[0].content_pic = ''
                      this.stop = 0
                      this.gotoBottom()
                    },
                  })
                }
              });
            }
          },
        });
      },
      // 初始化页面到达底部
      gotoBottom() {
        var timer = setTimeout(() => {
          this.scrollBottom()
        }, 50)
      },
      // textarea 获取焦点时自动滚动到页面最底部
      scrollBottom() {
        uni.pageScrollTo({
          scrollTop: 100000,
          duration: 0
        });
      }
    }
  }
</script>

<style lang="scss">
  page {
    background: #f4f4f6;
  }

  // 消息渲染
  .message_list {
    width: 100%;

    .message_item {
      padding-left: 25rpx;
      padding-right: 25rpx;
      margin-bottom: 25rpx;

      .message_right {
        display: flex;
        justify-content: flex-end;
        width: 100%;

        .picture {
          max-width: 350rpx;
          margin-right: 30rpx;

          image {
            max-width: 350rpx;
          }
        }

        .triangle {
          width: 0;
          height: 0;
          overflow: hidden;
          margin-top: 23rpx;
          font-size: 0;
          line-height: 0;
          border-width: 15rpx;
          border-style: dashed dashed dashed solid;
          border-color: transparent transparent transparent #71ffad;
        }

        .text {
          background-color: #71ffad;
          color: #fff;
          line-height: 42rpx;
          max-width: 457rpx;
          letter-spacing: 3rpx;
          font-size: 32rpx;
          padding: 15rpx 20rpx;
          border-radius: 10rpx;
        }
      }

      .message_left {
        display: flex;
        width: 100%;

        .picture {
          max-width: 350rpx;
          margin-left: 30rpx;

          image {
            max-width: 350rpx;
          }
        }

        .triangle {
          width: 0;
          height: 0;
          overflow: hidden;
          margin-top: 23rpx;
          font-size: 0;
          line-height: 0;
          border-width: 15rpx;
          border-style: dashed solid dashed dashed;
          border-color: transparent #5ce5e3 transparent transparent;
        }

        .text {
          background-color: #5ce5e3;
          color: #fff;
          line-height: 42rpx;
          font-size: 32rpx;
          max-width: 457rpx;
          padding: 15rpx 20rpx;
          border-radius: 10rpx;
        }
      }

      .avatarUrl {
        width: 76rpx;
        height: 76rpx;
        border-radius: 20rpx;
      }
    }
  }

  .bottom_area {
    width: 100%;
    height: 96rpx;
  }

  .bottom_box {
    display: flex;
    position: fixed;
    width: 100%;
    min-height: 95rpx;
    background-color: #f4f4f4;
    border-top: 1px solid #cccccc;
    bottom: 0;

    .inputText {
      width: 530rpx;
      font-size: 34rpx;
      margin-top: 15rpx;
      margin-bottom: 15rpx;
      margin-left: 15rpx;
      min-height: 55rpx;
      line-height: 34rpx;
      padding-left: 20rpx;
      padding-top: 10rpx;
      background-color: #fff;
      border-radius: 10rpx;
    }

    .sendButton {
      position: absolute;
      right: 30rpx;
      bottom: 20rpx;
      word-break: break-all;
      overflow: visible;
      width: 130rpx;
      height: 55rpx;
      text-align: center;
      font-size: 32rpx;
      line-height: 55rpx;
      color: #fff;
      background-color: #2fe767;
    }

    .sendPic {
      position: absolute;
      bottom: 20rpx;
      right: 70rpx;
    }
  }
</style>
